package uutalk.netcloud.talk.app.ui.Activity;


import android.graphics.Bitmap;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.apkfuns.logutils.LogUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.makeramen.roundedimageview.RoundedImageView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import uutalk.netcloud.talk.R;
import uutalk.netcloud.talk.app.Constants;
import uutalk.netcloud.talk.app.ui.adapter.GroupMemberAdapter;
import uutalk.netcloud.talk.base.android.BaseActivity;
import uutalk.netcloud.talk.base.mqtt.MQTTManager;
import uutalk.netcloud.talk.base.mqtt.PublishFactory;
import uutalk.netcloud.talk.base.mqtt.event.MqttMessageEvent;
import uutalk.netcloud.talk.base.mqtt.model.Publication;
import uutalk.netcloud.talk.base.util.LanguageUtil;
import uutalk.netcloud.talk.base.util.VibratorUtil;
import uutalk.netcloud.talk.base.util.thirdpart.ImageLoadListener;
import uutalk.netcloud.talk.base.util.thirdpart.ImageLoader;
import uutalk.netcloud.talk.base.util.thirdpart.QiNiuManager;
import uutalk.netcloud.talk.base.util.thirdpart.TalkManager;
import uutalk.netcloud.talk.base.util.thirdpart.UserManager;
import uutalk.netcloud.talk.base.util.view.ToastUtil;
import uutalk.netcloud.talk.base.widget.AudioSpeekButton;
import uutalk.netcloud.talk.model.BussinessBeanFactory;
import uutalk.netcloud.talk.model.bean.CMDConstant;
import uutalk.netcloud.talk.model.bean.DBEntityManager;
import uutalk.netcloud.talk.model.bean.GroupInfoBean;
import uutalk.netcloud.talk.model.bean.GroupMember;
import uutalk.netcloud.talk.model.bean.GroupMemberWrap;
import uutalk.netcloud.talk.model.bean.QuitGroupRsp;

/**
 * A simple {@link Fragment} subclass.
 */
public class GroupMainActivity extends BaseActivity {

    @BindView(R.id.ivBack)
    ImageView ivBack;

    @BindView(R.id.tvLeft)
    TextView tvLeft;

    @BindView(R.id.tvTitle)
    TextView tvTitle;

    @BindView(R.id.tvRight)
    TextView tvRight;

    @BindView(R.id.recyclerview)
    RecyclerView recyclerView;

    @BindView(R.id.ll_group)
    LinearLayout ll_group;

    @BindView(R.id.rl_group)
    RelativeLayout rl_group;

    @BindView(R.id.headIV)
    RoundedImageView roundedImageView;



    @BindView(R.id.start_talk)
    AudioSpeekButton startTalkView;


    private String groupID;
    private String groupName;
    GroupInfoBean groupInfoBean;
    boolean isSpeak;
    private boolean lockLongPressKey = false;


    @Override
    public boolean supportActionbar() {
        return false;
    }

    @Override
    public boolean autoBindEvent() {
        return true;
    }

    @Override
    public int layoutId() {
        return R.layout.fragment_group_main;
    }



    @Override
    public void init() {
        tvLeft.setVisibility(View.GONE);
        tvRight.setVisibility(View.GONE);
//        ivBack.setImageResource(R.mipmap.ic_top_setting);
        ivBack.setImageResource(R.drawable.icon_back_selector);

        groupID = getIntent().getStringExtra(Constants.KEY_UID);
        groupName = getIntent().getStringExtra(Constants.KEY_TITLE);

        tvTitle.setText(LanguageUtil.getStringById(R.string.str_group_info)+groupName);
        recyclerView.setLayoutManager(new GridLayoutManager(mActivity, 4));
        if(TextUtils.isEmpty(groupID)){
            finish();
            return;
        }
        requestGroupMember(groupID);
        requestGroupInfo();
        //加入群
        TalkManager.getInstance().joinChannel(groupID,UserManager.getInstance().getUserInfo().getUser_id());
        ImageLoader.loadImageBitmap(mActivity, QiNiuManager.QINIU_HOST + UserManager.getInstance().getUserInfo().getPicture(), new ImageLoadListener() {
            @Override
            public void onLoadComplete(Object t) {
                roundedImageView.setImageBitmap((Bitmap)t);
            }

            @Override
            public void onLoadFail() {

            }
        });

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMqttMessageEvent(MqttMessageEvent event) {
        if (CMDConstant.GET_GROUP_INFO_RESP_CMD.equals(event.getMessage().getCmd())) {
            progressHudUtil.dismissProgressHud();
            groupInfoBean = JSON.parseObject(event.getMessage().toString(), GroupInfoBean.class);
            if (groupInfoBean.isOk()) {
                initActInfoLayout();
            } else {
                ToastUtil.makeToast(groupInfoBean.getError_msg());
            }
        } else if (CMDConstant.LEAVE_GROUP_RESP_CMD.equals(event.getMessage().getCmd())) {
            //离开群
            progressHudUtil.dismissProgressHud();
            QuitGroupRsp group = JSON.parseObject(event.getMessage().toString(), QuitGroupRsp.class);
            if (group.isOk()) {
                ToastUtil.makeToast(LanguageUtil.getStringById(R.string.str_leave_group));
                finish();
            } else {
                ToastUtil.makeToast(group.getError_msg());
            }
        } else if(CMDConstant.DISMISS_GROUP_RESP_CMD.equals(event.getMessage().getCmd())){
            //退出群
            progressHudUtil.dismissProgressHud();
            QuitGroupRsp group = JSON.parseObject(event.getMessage().toString(), QuitGroupRsp.class);
            if (group.isOk()) {
                finish();
            } else {
                ToastUtil.makeToast(group.getError_msg());
            }
        } else if(CMDConstant.QUIT_GROUP_RESP_CMD.equals(event.getMessage().getCmd())){
            //退出群
            progressHudUtil.dismissProgressHud();
            QuitGroupRsp group = JSON.parseObject(event.getMessage().toString(), QuitGroupRsp.class);
            if (group.isOk()) {
                finish();
            } else {
                ToastUtil.makeToast(group.getError_msg());
            }
        } else if(CMDConstant.GET_GROUP_MEMBER_RESP_CMD.equals(event.getMessage().getCmd())){
            progressHudUtil.dismissProgressHud();
            //请求服务器
            GroupMemberWrap groupMemberWrap = JSON.parseObject(event.getMessage().toString(), GroupMemberWrap.class);
            if (groupMemberWrap.isOk()) {
                if (groupMemberWrap.getMember_list() != null && groupMemberWrap.getMember_list().size() > 0) {
                    List<GroupMember> groupMembers = groupMemberWrap.getMember_list();
                    int size = groupMembers.size();
                    GroupMember groupMember;
                    //保存服务器返回的所有群组成员保存到数据库中
                    for (int i = 0; i < size; i++) {
                        groupMember = groupMembers.get(i);
                        groupMember.setGroup_id(groupID);
                        DBEntityManager.saveGroupMember(groupMember);
                    }
                    Collections.sort(groupMembers);
                    GroupMemberAdapter groupMemberAdapter = new GroupMemberAdapter(mActivity, groupMembers);
                    recyclerView.setAdapter(groupMemberAdapter);
                }
            } else {

            }

        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
            switch (keyCode) {
                case KeyEvent.KEYCODE_VOLUME_DOWN:
                    Log.v(TAG,"onKeyDown event.getRepeatCount() "+event.getRepeatCount());
                    if(event.getRepeatCount()==0){
                        event.startTracking();
                    }
                    return true;
            }
            return super.onKeyDown(keyCode, event);
    }


    @Override
    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                Log.e(TAG, "onKeyLongPress KeyEvent.KEYCODE_VOLUME_DOWN");
                tvTitle.setText(LanguageUtil.getStringById(R.string.talking));
                TalkManager.getInstance().openMic(true);
                lockLongPressKey = true;
                return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                if(lockLongPressKey){
                    tvTitle.setText(LanguageUtil.getStringById(R.string.str_group_info)+groupName);
                    Log.e(TAG, "onKeyUp 按键弹起来了。");
                    lockLongPressKey = false;
                    TalkManager.getInstance().openMic(false);
                    return true;
                }
                if (event.getRepeatCount() == 0) {
                    Log.e(TAG, "onKeyUp event.getRepeatCount() == 0");
                }
        }
        return super.onKeyDown(keyCode, event);
    }


    @OnClick({R.id.ivBack, R.id.headIV,R.id.ivHorn})
    public void OnViewClick(View view){
        switch (view.getId()){
            case R.id.ivBack:{
                finish();
            } break;
            case R.id.headIV:{
                //上传头像
                PictureSelector.create(this).openGallery(PictureMimeType.ofImage()).selectionMode(PictureConfig.SINGLE).forResult(PictureConfig.CHOOSE_REQUEST);
            } break;
            case R.id.ivHorn:{

            } break;
            default:
                break;
        }
    }

    @Override
    public void onBackPressed() {
        finish();
    }

    @Override
    public void gc() {
        super.gc();
        TalkManager.getInstance().leaveChannel();
    }

    void initActInfoLayout() {
        rl_group.setVisibility(View.VISIBLE);
    }

    //离开群
    public boolean leaveGroup(String groupId) {
        if (MQTTManager.getInstance().isConnected()) {
            progressHudUtil.showProgressHud(false);
            Publication publication = PublishFactory.createPublication(BussinessBeanFactory.createQuitActivityBean(CMDConstant.LEAVE_GROUP_CMD, groupId));
            MQTTManager.getInstance().publish(publication);
            return true;
        } else {
            ToastUtil.makeToast(LanguageUtil.getStringById(R.string.get_data_erro));
            return false;
        }

    }

    /**
     * 是否按住了说话按钮
     *
     * @param isPress
     */
    private void onTalkBtnPress(boolean isPress, boolean isVibrate) {
        if (isPress) {
            if (isSpeak) {
                return;
            }
            isSpeak = true;
            if(isVibrate){
                VibratorUtil.Vibrate(mActivity, 100);
            }
            TalkManager.getInstance().openMic(true);
            LogUtils.e("按下说话");
        } else {
            if (!isSpeak) {
                return;
            }
            LogUtils.e("停止说话");
            isSpeak = false;
            TalkManager.getInstance().openMic(false);
        }
    }


    /**
     * 设置说话按点触摸事件
     */
    public void setTalkBtnTouchEvent() {

//        startTalkView.setOnTouchListener((View v, MotionEvent event) -> {
//            if (event.getAction() == MotionEvent.ACTION_DOWN) {
//                onTalkBtnPress(true, true);
//            } else if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL || event.getAction() == MotionEvent.ACTION_OUTSIDE) {
//                onTalkBtnPress(false, true);
//            }
//            return true;
//        });
    }

    /**
     * 请求群组信息
     */
    public void requestGroupInfo() {
        if (MQTTManager.getInstance().isConnected()) {
            progressHudUtil.showProgressHud(false);
            Publication publication = PublishFactory.createPublication(BussinessBeanFactory.createGetGroupInfoBean(groupID));
            MQTTManager.getInstance().publish(publication);
            Log.e(TAG, "requestGroupInfo groupID>>"+groupID);
        } else {
            ToastUtil.makeToast(R.string.request_error);
        }
    }

    /**
     * 获取群组成员
     *
     * @param groupId
     */
    public void requestGroupMember(String groupId) {
        if(!TextUtils.isEmpty(groupId)){
            if (MQTTManager.getInstance().isConnected()) {
                progressHudUtil.showProgressHud();
                Publication publication = PublishFactory.createPublication(BussinessBeanFactory.createGetGroupMemberBean(groupId));
                MQTTManager.getInstance().publish(publication);
            } else {
                ToastUtil.makeToast(R.string.request_error);
            }
        }
    }

    /**
     * 群成员响应
     * @param event
     */
    private void onGroupMemberRespCMD(MqttMessageEvent event) {
        GroupMemberWrap groupMemberWrap = JSON.parseObject(event.getMessage().toString(), GroupMemberWrap.class);
        if (groupMemberWrap.isOk()) {
            if (groupMemberWrap.getMember_list() != null && groupMemberWrap.getMember_list().size() > 0) {
                List<GroupMember> groupMembers = groupMemberWrap.getMember_list();
                int size = groupMembers.size();
                GroupMember groupMember;
                //保存服务器返回的所有群组成员保存到数据库中
                for (int i = 0; i < size; i++) {
                    groupMember = groupMembers.get(i);
                    groupMember.setGroup_id(groupID);
                    DBEntityManager.saveGroupMember(groupMember);
                }
            }
        } else {

        }
    }

    /**
     * 判断是否是群主创建人
     * @return
     */
    private boolean isGroupOwner(){
        Log.e("GroupInfoFragment", "isGroupOwner>>"+groupInfoBean.getOwner_id() + "userid>>" + UserManager.getInstance().getUserInfo().getUser_id());
        if(groupInfoBean != null){
            if(groupInfoBean.getOwner_id().equals(UserManager.getInstance().getUserInfo().getUser_id())){
                return true;
            }
        }
        return false;
    }
}
